package com.github.yoojia.mqtt.boot.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.0
 */
public class Keeper {

    public static final Logger LOGGER = LoggerFactory.getLogger(Keeper.class);

    private final Runnable mShutdown;
    private final CountDownLatch mExitSignal = new CountDownLatch(1);

    private final Thread mKeepThread = new Thread(new Runnable() {
        @Override public void run() {
            try {
                mExitSignal.await();
            } catch (InterruptedException e) {
                LOGGER.error("KeepThread interrupted", e);
            }
        }
    });

    public Keeper(Runnable shutdown) {
        mShutdown = shutdown;
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override public void run() {
                mShutdown.run();
                mExitSignal.countDown();
            }
        }));
    }

    public void run() throws InterruptedException {
        mKeepThread.start();
        mKeepThread.join();
    }
}
